package org.pzy.java.reflect;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @Author: DRevelation
 * @Date: 2022/2/23 10:15
 */
public class Main {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException,
            IllegalAccessException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {

        // 获取类
        Class<?> targetClass = Class.forName("org.pzy.java.reflect.TargetObject2");
        @Deprecated
//        TargetObject2 targetObject = (TargetObject2) targetClass.newInstance();
        // 获取对象
        TargetObject2 targetObject = (TargetObject2) targetClass.getDeclaredConstructor().newInstance();
        System.out.println("targetObject = " + targetObject);

        // 获取类中所有定义的方法
        Method[] methods = targetClass.getDeclaredMethods();
        for (Method method : methods) {
            System.out.println("field.getName() = " + method.getName());
        }

        // 获取指定方法并调用
        Method publicMethod = targetClass.getDeclaredMethod("publicMethod", String.class);
        publicMethod.invoke(targetObject, "Java Guide");
        // 调用private方法
        Method privateMethod = targetClass.getDeclaredMethod("privateMethod");
        privateMethod.setAccessible(true);
        privateMethod.invoke(targetObject);

        // 获取指定参数并对参数修改
        Field field = targetClass.getDeclaredField("value");
        field.setAccessible(true);
        field.set(targetObject, "Pzy");

        privateMethod.invoke(targetObject);

    }
}
